<script setup lang="ts">
import { ref } from 'vue'
import { timeFormat, timeFormat_2 } from '@/hooks/util'
import { useRoute, useRouter } from 'vue-router'
import * as cardCouponsApi from '@/api/cardCoupons'
import { message } from 'ant-design-vue'
import OkAuthorization from './components/OkAuthorization.vue'
import EditAuthorization from './components/EditAuthorization.vue'

const router = useRouter()

const okAuthorizationRef = ref()
const editAuthorizationRef = ref()

interface Pagination {
  page: number
  pageSize: number
  total: number
  current?: number
  onChange: Function
  showSizeChanger: boolean
  showQuickJumper: boolean
}

const handlePageChange = (page: any, pageSize: any) => {
  pagination.value.pageSize = pageSize
  searchParams.value.pageSize = pageSize
}

const pagination = ref<Pagination>({
  page: 1,
  pageSize: 10,
  total: 0,
  onChange: handlePageChange,
  showSizeChanger: true,
  showQuickJumper: true
})
let loading = ref<boolean>(false)

interface SearchParams {
  currentPage: number
  pageSize: number
  remark?: string | undefined
}
const searchParams = ref<SearchParams>({
  currentPage: pagination.value.page,
  pageSize: pagination.value.pageSize,
})

const dataSource = ref([])
const columns = [
  {
    title: 'id',
    key: 'id',
    width: 180,
  },
  {
    title: '备注',
    key: 'remark',
    width: 180,
  },
  {
    title: 'Key',
    key: 'appId',
    width: 180,
  },
  {
    title: 'Secret',
    key: 'secret',
    width: 180,
  },
  {
    title: '创建时间',
    key: 'createTime',
    width: 180,
  },
  {
    key: 'action',
    title: '操作',
    width: 150,
    fixed: 'right',
  },
]

// 表格多选
const selectedRowKey = ref<Array<any>>([])
const selectedRow = ref<Array<object>>([])
const onSelectChange = (selectedRowKeys: any[], selectedRows: any[]) => {
  selectedRowKey.value = selectedRowKeys
  selectedRow.value = selectedRows
}

// 翻页
const changePage = (e: any) => {
  pagination.value.current = e.current
  pagination.value.pageSize = e.pageSize

  searchParams.value.currentPage = pagination.value.current as number
  getList()
}

const getList = async () => {
  loading.value = true
  try {
    let { state, data, message: msg } = await cardCouponsApi.xcUserDataPageList(searchParams.value)
    if (state === 200) {
      data.list.forEach((item: { isRemarkShow: boolean }) => {
        item.isRemarkShow = false
      })
      dataSource.value = data.list
      pagination.value.total = Number(data.totalCount)
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
  loading.value = false
}

onMounted(() => {
  getList()
})

defineExpose({
  getList,
})

// 查询
const formRef = ref()
interface FormState {
  remark?: string
}
const formState = reactive<FormState>({})

const search = () => {
  pagination.value.current = 1
  searchParams.value.currentPage = 1

  formRef.value.validate().then(() => {
    if (formState.remark != '') {
      searchParams.value.remark = formState.remark
    }
    getList()
  })
}

// 重置
const reset = () => {
  pagination.value.current = 1
  searchParams.value.currentPage = 1

  formRef.value.resetFields()
  Reflect.deleteProperty(searchParams.value, 'remark')
  getList()
}

// 新增星驰卡券账户
const toAuthorization = async () => {
  okAuthorizationRef.value.showModal()
}

// 同步卡券
const syncCoupons = async (userId: string) => {
  try {
    let { state, message: msg } = await cardCouponsApi.synchronizationCardRollNineOneData({
      userId,
    })
    if (state == 200) {
      message.success('同步请求发送成功')
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('同步失败~')
  }
}

const changeRouter = () => {
  router.push('/xing-chi-category-list')
}

// 修改备注
const EditRemarkSet = async (record: any) => {
  record.isRemarkShow = true
}

// 备注提交 -
const handleRemark = async (record: any) => {
  record.isRemarkShow = false
  let params = {
    id: record.id,
    remark: record.remark,
  }
  try {
    const { state, message: msg } = await cardCouponsApi.xcUserRemarkDataEdit(params)
    if (state === 200) {
      message.success('备注保存成功')
      getList()
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}

const del = async id => {
  try {
    const { state, message: msg } = await cardCouponsApi.xcUserDataDelete({ id })
    if (state === 200) {
      message.success('删除成功~')
      getList()
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}

const edit = (record: any) => {
  editAuthorizationRef.value.showModal(record)
}
</script>

<template>
  <div>
    <div class="searchBox">
      <a-form ref="formRef" layout="inline" :model="formState">
        <a-form-item label="备注" name="remark">
          <a-input v-model:value="formState.remark" placeholder="备注" />
        </a-form-item>

        <a-form-item>
          <a-button type="primary" @click="search">搜索</a-button>
          <a-button @click="reset">重置</a-button>
          <a-button type="primary" @click="toAuthorization">新增星驰卡券账户</a-button>
        </a-form-item>
      </a-form>
    </div>

    <a-alert
      description="小提示：只要鼠标在表格上，按住左Shift键并滚动鼠标滚轮就可以横向滚动表格"
      type="info"
      banner
      style="margin-bottom: 10px; padding: 10px"
    />

    <a-table
      style="overflow-x: scroll"
      :columns="columns"
      :data-source="dataSource"
      :pagination="pagination"
      :loading="loading"
      @change="changePage"
      rowKey="id"
      :row-selection="{ selectedRowKeys: selectedRowKey, onChange: onSelectChange }"
      :scroll="{ x: 100 }"
      size="small"
    >
      <template #emptyText>
        <a-empty description="暂无数据" />
      </template>

      <template #headerCell="{ column }"></template>

      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'id'">
          {{ record.id }}
        </template>

        <template v-else-if="column.key === 'remark'">
          <div style="display: flex; align-items: center">
            <a-tooltip placement="top" v-if="!record.isRemarkShow">
              <template #title>
                <span>{{ record.remark }}</span>
              </template>
              <span class="hiddenText">{{ record.remark }}</span>
            </a-tooltip>
            <a-input
              v-else
              v-model:value="record.remark"
              @blur="handleRemark(record)"
              style="border: 0"
            />
            <EditOutlined
              @click="EditRemarkSet(record)"
              v-if="!record.isRemarkShow"
              style="margin-left: 6px; color: #1890ff"
            />
          </div>
        </template>

        <template v-else-if="column.key === 'createTime'">
          {{ timeFormat_2(record.createTime) }}
        </template>

        <template v-else-if="column.key === 'appId'">
          <a-tooltip placement="top" v-if="!record.isRemarkShow">
            <template #title>
              <span>{{ record.appId }}</span>
            </template>
            <span class="hiddenText">{{ record.appId }}</span>
          </a-tooltip>
        </template>

        <template v-else-if="column.key === 'secret'">
          <a-tooltip placement="top" v-if="!record.isRemarkShow">
            <template #title>
              <span>{{ record.secret }}</span>
            </template>
            <span class="hiddenText">{{ record.secret }}</span>
          </a-tooltip>
        </template>

        <template v-else-if="column.key === 'action'">
          <div style="width: 100px; margin: 0; padding: 0">
            <!-- <a @click="syncCoupons(record.userId)">同步卡券</a> -->
            <a @click="changeRouter">卡种列表</a>
          </div>
          <div style="width: 100px; margin: 0; padding: 0">
            <a-popconfirm
              title="确定删除？"
              ok-text="是"
              cancel-text="否"
              @confirm="del(record.id)"
            >
              <a>删除</a>
            </a-popconfirm>
          </div>
          <div style="width: 100px; margin: 0; padding: 0">
            <a @click="edit(record)">编辑</a>
          </div>
        </template>
      </template>
    </a-table>

    <OkAuthorization ref="okAuthorizationRef" @refresh="getList"></OkAuthorization>
    <EditAuthorization ref="editAuthorizationRef" @refresh="getList"></EditAuthorization>
  </div>
</template>

<style lang="less" scoped>
.hiddenText {
  display: inline-block;
  max-width: 160px;
  overflow: hidden;
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
  line-height: 16px;
}

.searchBox {
  margin-bottom: 10px;
  display: flex;

  input {
    width: 200px;
    margin-right: 10px;
  }

  button {
    margin-right: 10px;
  }
}

a:hover {
  color: red;
}
</style>
